package com.sto.stoapp.thread;

import static com.sto.stoapp.http.ServerSmsHttpManager.FORMAT;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.BillcodeManager;
import com.sto.stoapp.entity.BaseEntity;
import com.sto.stoapp.entity.BillcodeEntity;
import com.sto.stoapp.entity.JsonEntity;
import com.sto.stoapp.http.JsonUploadHttpManager;
import com.sto.stoapp.md5.Md5;
import com.sto.stoapp.util.UnifiedStaticType;

/**
 * 面单发放下载
 * 
 * @author hb
 * 
 */
public class CodeIssueThread extends BaseThread {
	private Handler handler;
	private int what;
	private final String URL = "http://140.206.185.9:22210/stLogisticsPlatform_track/releaseRecordQuery.action";
	private final String key = "NmJxbTU2dUw2WUNmNllDUw==";// 固定的key
	private String todayDate = "";

	public CodeIssueThread(Context context, int what, Handler handler) {
		super(context);
		this.handler = handler;
		this.what = what;
	}

	@SuppressWarnings("null")
	@Override
	public void run() {
		Message message = handler.obtainMessage();
		message.obj = "";
		String result = "";
		try {
			JsonEntity jsonEntity = new JsonEntity();

			String jsonData = getJsonData();
			Md5 md5 = new Md5();
			String signKey = md5.getMD5Hex(jsonData + key);
			//
			// String base64Key = Base64.encodeToString(
			// signKey.getBytes(FORMAT), Base64.DEFAULT);

			String base64Key = new String(Base64.encodeBase64(signKey
					.getBytes(FORMAT)));
			jsonEntity.setURL(URL);
			jsonEntity.setData(jsonData);
			jsonEntity.setKey(base64Key);

			jsonEntity.setDataName("logistics_interface");
			jsonEntity.setKeyName("data_digest");

			result = new JsonUploadHttpManager().postData(jsonEntity);
			System.out.println("result======" + result);
			if (personJsonData(result)) {
				message.obj = "面单发放表下载成功";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			message.what = what;
			handler.sendMessage(message);
		}

		super.run();
	}

	// /** 把上传的数据打包成Json协议 **/
	// @SuppressLint("SimpleDateFormat")
	// private String getJsonData() throws JSONException {
	// SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	// String date = sDateFormat.format(new java.util.Date());
	//
	// JSONObject json = new JSONObject();
	// json.put("starttime", "2013-04-23");
	// json.put("endtime", "2013-04-23");
	// json.put("sitecode", "519000");
	//
	// return json.toString();
	// }

	/** 把上传的数据打包成Json协议 **/
	@SuppressLint("SimpleDateFormat")
	private String getJsonData() throws JSONException {
		String month = null;

		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				UnifiedStaticType.SIMPLE_DATE_FORMAT);
		todayDate = sDateFormat.format(new java.util.Date());

		if (StoFilePreference.getInstance(context).getBillCodeIssueTime()
				.equals("")) {
			// 半年的时间
			Calendar cal1 = Calendar.getInstance();
			cal1.add(Calendar.MONTH, -6);
			month = new SimpleDateFormat(UnifiedStaticType.SIMPLE_DATE_FORMAT)
					.format(cal1.getTime());
		} else {
			month = StoFilePreference.getInstance(context)
					.getBillCodeIssueTime();
		}

		JSONObject json = new JSONObject();
		json.put("sitecode", StoFilePreference.getInstance(context)
				.getSiteCode());
		json.put("starttime", month);
		json.put("endtime", todayDate);

		return json.toString();
	}

	/** 解析服务器返回数据 **/
	private boolean personJsonData(String result) throws JSONException {

		boolean ret = false;
		List<BaseEntity> billCodeList = new ArrayList<BaseEntity>();

		JSONObject json = new JSONObject(result);
		String success = json.getString("success");

		ret = Boolean.parseBoolean(success);
		System.out.println("success==============" + ret);
		// 返回成功
		if (ret) {
			JSONArray data = json.getJSONArray("responseitems");
			for (int i = 0; i < data.length(); i++) {
				JSONObject info = data.getJSONObject(i);
				BillcodeEntity billcodeEntity = new BillcodeEntity();

				billcodeEntity.setSiteName(info.getString("sitename"));
				billcodeEntity
						.setBillcodeBegin(info.getString("billcodebegin"));
				billcodeEntity.setBillcodeEnd(info.getString("billcodeend"));
				billcodeEntity.setExtendDate(info.getString("extenddate"));
				billcodeEntity.setReleaseQuantity(info
						.getString("releasequantity"));
				billCodeList.add(billcodeEntity);
			}
			if (billCodeList.size() > 0) {
				BillcodeManager.getInstance(context).insertList(billCodeList);
			}
			StoFilePreference.getInstance(context).setBillCodeIssueTime(
					todayDate);
		}
		return ret;
	}
}
